#include <crtdbg.h>
#include <direct.h>
#include <stdio.h>

#include "toolbox_interchange.hpp"
#include "rdxsupport.hpp"

using namespace RDX;
using namespace RDX::ObjectManagement;
using namespace RDX::Programmability;


int RDXToBin_Main()
{
	if(toolResources.argc < 3 || strcmp(toolResources.argv[2], "-rdxtextfirst"))
	{
		fprintf(stderr, "Syntax: rdxtobin -rdxtextfirst <Package list>");
		fprintf(stderr, "        Packages must be detectable via TDPTools.zonepolicy");
		return -1;
	}

	RDX::OperationContext ctx(toolResources.objm);

	for(int i=3;i<toolResources.argc;i++)
	{
		CRef<const String> str1 = toolResources.objm->CreateStringASCII(&ctx, toolResources.argv[i]);
		CRef<const String> str2 = toolResources.objm->CreateStringASCII(&ctx, ".a");
		CRef<const String> symbolStr = toolResources.objm->CreateStringConcatenated(&ctx, str1, str2);

		// Find the domain
		Domain domain = toolResources.pkgHost->DomainForSymbolName(toolResources.objm, symbolStr);
		if(domain == DOMAIN_Invalid)
		{
			fprintf(stderr, "Couldn't resolve domain package for %s", toolResources.argv[i]);
			return -1;
		}

		printf("%s loading ...", toolResources.argv[i]);
		CRef<Package> pkg = toolResources.objm->LoadPackage(&ctx, domain, toolResources.pkgHost);
		if(pkg == NULL)
		{
			fprintf(stderr, "\n\nCouldn't load package for %s", toolResources.argv[i]);
			return -1;
		}

		printf("    saving ...", toolResources.argv[i]);
		toolResources.objm->SavePackage(&ctx, domain, toolResources.pkgHost);
		printf("Done\n", toolResources.argv[i]);
	}

	return 0;
}

